<script setup>
import { onMounted, ref } from "vue";
import { getCourseListApi,getCoashListApi,getUserListApi,addCourseApi,getCourseByIdApi,deleteCourseApi,updateCourseApi } from "@/api/course";
import { Edit } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'

onMounted(() => {
    getCourseList();
    getCoashList();
    getUserList();
});

// 时间轴数据
const TimeToDay = ref([
    "课程表",
    "8:00-9:00",
    "9:00-10:00",
    "10:00-11:00",
    "11:00-12:00",
    "12:00-13:00",
    "13:00-14:00",
    "14:00-15:00",
    "15:00-16:00",
    "16:00-17:00",
    "17:00-18:00",
    "18:00-19:00",
    "19:00-20:00",
    "20:00-21:00",
    "21:00-22:00",
    "22:00-23:00",
]);
// 日期栏数据
const DayAndWeekList = ref({
    dateList: [],
    weekList: [],
});
// 课程表数据
const Course = ref([]);
const isLoading = ref(true);

// 获取课程表数据
const getCourseList = async () => {
    await getCourseListApi().then((res) => {
        console.log(res.data);
        Course.value = res.data.courseList;
        DayAndWeekList.value.dateList = res.data.dateList;
        DayAndWeekList.value.weekList = res.data.weekList;
        setTimeout(() => {
            isLoading.value = false; // 模拟加载完成
        }, 500); // 延迟500ms显示数据
    });
};

//弹窗
const centerDialogVisible = ref(false);
const add_upate = ref(true);
const CourseObject = ref({
    id: "",
    courseName: "",
    startTime: "",
    lessonLen: "",
    childId: [],
    coashId: []
});

// 提示框数据
const coashInput = ref('')
const childInput = ref('')
const coashLinks = ref([])
const childLinks = ref([])
// 获取全部教练名字数据
const getCoashList = async () => {
    await getCoashListApi().then(res => {
        coashLinks.value = res.data
        console.log("获取教练名",coashLinks.value)
    })
}

// 创建教练过滤器
const createFilter = (coashQueryString) => {
  return (item) => {
    return (
        item.username.toLowerCase().includes(coashQueryString.toLowerCase()))
  }
}

// 教练查询建议方法
const coashQuerySearch = (coashQueryString, cb) => {
  const results = coashQueryString
    ? coashLinks.value.filter(createFilter(coashQueryString))
    : coashLinks.value
  cb(results)
}
// 教练选择下拉框数据
const coashHandleSelect = (item) => {
    coashInput.value = item.username
}
// 获取用户全部名字数据
const getUserList = async () => {
    await getUserListApi().then(res => {
        childLinks.value = res.data
        console.log("获取用户名：",childLinks.value)
    })
}
// 创建用户过滤器
const createFilter1 = (childQueryString) => {
  return (items) => {
    console.log("过滤器输入：", items);
    return (
        items.name.toLowerCase().includes(childQueryString.toLowerCase()))
  }
}

//显示数据
const coashArr = ref([[],[]])
const childArr = ref([[],[]])
const coashArrAdd = () => {
    if(coashInput.value == ''){
        ElMessage.warning('输入框不能为空')
    }else if(coashLinks.value.find(item => item.username == coashInput.value) == undefined){
        ElMessage.warning('该教练不存在')
    }else{
        coashArr.value[0].push(coashInput.value)
        coashArr.value[1].push(coashLinks.value.find(item => item.username == coashInput.value).id)
        coashInput.value = ''
    }
}
const coashArrDel = () => {
    coashArr.value[0] = coashArr.value[0].filter((item) => item !== coashInput.value)
    coashArr.value[1] = coashArr.value[1].filter((item) => item !== coashLinks.value.find(item => item.username == coashInput.value).id)
    coashInput.value = ''
}
const childArrAdd = () => {
    if(childInput.value == ''){
        ElMessage.warning('输入框不能为空')
    }else if(childLinks.value.find(item => item.name == childInput.value) == undefined){
        ElMessage.warning('该用户不存在')
    }else{
        childArr.value[0].push(childInput.value)
        childArr.value[1].push(childLinks.value.find(item => item.name == childInput.value).id)
        childInput.value = ''
    }
}
const childArrDel = () => {
    childArr.value[0] = childArr.value[0].filter((item) => item !== childInput.value)
    childArr.value[1] = childArr.value[1].filter((item) => item !== childLinks.value.find(item => item.name == childInput.value).id)
    childInput.value = ''
}
// 用户查询建议方法
const childQuerySearch = (childQueryString, cb1) => {
    console.log("搜索关键词：", childQueryString);
  const results = childQueryString
    ? childLinks.value.filter(createFilter1(childQueryString))
    : childLinks.value
    console.log("过滤结果：", results);
  cb1(results)
}
// 用户选择下拉框数据
const childHandleSelect = (items) => {
    childInput.value = items.name
}
//更新弹窗
const update = (id) => {
    coashArr.value = [[],[]]
    childArr.value = [[],[]]
    getCourseById(id)
};
//获取单个课表详细信息
const getCourseById = async (id) =>{
    await getCourseByIdApi(id).then(res => {
        CourseObject.value = res.data
        console.log("获取课程表：", CourseObject.value);
        const Coarr = CourseObject.value.coashNamelist 
        const Charr = CourseObject.value.childNamelist
        for(let i = 0; i < Coarr.length; i++){
            coashArr.value[0].push(Coarr[i].username)
            coashArr.value[1].push(Coarr[i].id)
        }
        for(let i = 0; i < Charr.length; i++){
            childArr.value[0].push(Charr[i].name)
            childArr.value[1].push(Charr[i].id)
        }
        console.log("教练列表：", coashArr.value);
        console.log("用户列表：", childArr.value);
        centerDialogVisible.value = true
        add_upate.value = false
    })
}
//
const sumbitUpdate = async() => {
    let newarr = {}
    for(let key in CourseObject.value){
        if(key == 'courseName' || key == 'id' || key == 'lessonLen' || key == 'startTime'){
            newarr[key] = CourseObject.value[key]
        }
    }
    newarr['childId'] = childArr.value[1]
    newarr['coashId'] = coashArr.value[1]
    console.log("修改课程表：", newarr);
    await updateCourseApi(newarr).then(res => {
        ElMessage.success('修改成功')
        centerDialogVisible.value = false
        window.location.reload()
    })
}

// 删除课程表
const sumbitDelete = async(id) => {
    await deleteCourseApi(id).then(res => {
        ElMessage.success('删除成功')
        window.location.reload()
    })
}
//添加
const add = () => {
    centerDialogVisible.value = true;
    add_upate.value = true
};
//提交添加到数据库
const sumbitAdd = async() => {
    let setChild = new Set(childArr.value[1])
    let setCoash = new Set(coashArr.value[1])
    CourseObject.value.childId = Array.from(setChild)
    CourseObject.value.coashId = Array.from(setCoash)
    console.log("添加课程表：", CourseObject.value);
    await addCourseApi(CourseObject.value).then(res => {
        ElMessage.success('添加成功')
        centerDialogVisible.value = false
        window.location.reload()
    })
}
</script>

<template>
<div class="flex course">
    <!-- 左侧时间轴 -->
    <div class="left">
        <div class="box TimeToDay" v-for="(item, index) in TimeToDay" :key="index">{{ item }}</div>
    </div>

    <!-- 右侧课程表 -->
    <div class="right">
        <!-- 顶部日期栏 -->
        <div class="top box">
            <div v-for="(index) in DayAndWeekList.dateList.length" class="topBox" :key="index">
                <div>{{ DayAndWeekList.dateList[index - 1] }}</div>
                <div>{{ DayAndWeekList.weekList[index - 1] }}</div>
            </div>
        </div>

        <!-- 主体课程表 -->
        <div class="main flex">
            <div v-for="(col, colIndex) in DayAndWeekList.dateList.length" class="column" :key="colIndex" @click="add()">
                <div v-if="isLoading" class="loading-animation"></div>
                <div v-else>
                    <div v-if="Course[col - 1] == 'null'"></div>
                    <div
                        v-else
                        v-for="item in Course[col - 1]"
                        :key="item.id"
                        :style="{ height: item.lessonLen + 'px', top: item.distanceToEight + 'px' }"
                        class="CourseBos"
                        @click.stop="update(item.id)"
                    >
                        {{ item.courseName }}
                    </div>
                </div>
            </div>
        </div>


    </div>

</div>


    <!-- 添加弹窗 -->
    <el-dialog v-model="centerDialogVisible" title="课程表信息表" width="800" center>
        <!--第一行-->
        <div class="flex1 gap-4 items-between">
            <div>
                <span>课程名：</span>
                <el-input v-model="CourseObject.courseName" style="width: 240px" placeholder="输入课程名" />
            </div>
            <div>
                <span>开始时间：</span>
                <el-date-picker
                    v-model="CourseObject.startTime"
                    type="datetime"
                    placeholder="课程开始时间"
                    :shortcuts="shortcuts"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                />
            </div>
        </div>
        <!--第二行-->
        <div class="flex1 gap-4 items-between top10">
            <div>
                <span>课程时长：</span>
                <el-input v-model="CourseObject.lessonLen" style="width: 240px" placeholder="输入课程时长" />
            </div>
            <div>
                <span>结束时间：</span>
                <el-input style="width: 240px" placeholder="输入课程时长" disabled />
            </div>
        </div>
        <!--第三行-->
        <div class="flex1 gap-4 items-between top10">
            <!--教练-->
            <div>
                <span>上课教练：</span>
                <el-autocomplete
                    style="width: 140px; margin-right: 5px;"
                    v-model="coashInput"
                    :fetch-suggestions="coashQuerySearch"
                    popper-class="my-autocomplete"
                    placeholder="输入教练称号"
                    @select="coashHandleSelect"
                >
                    <template #suffix>
                        <el-icon class="el-input__icon" @click="handleIconClick">
                            <edit />
                        </el-icon>
                    </template>
                    <template #default="{ item }">
                        <div class="value">{{ item.username }}</div>
                    </template>
                </el-autocomplete>
                <el-button type="primary" @click="coashArrAdd">增加</el-button>
                <el-button type="danger" @click="coashArrDel">减少</el-button>
            </div>
            <!--学员-->
            <div>
                <span>上课儿童：</span>
                <el-autocomplete
                    style="width: 140px; margin-right: 5px;"
                    v-model="childInput"
                    :fetch-suggestions="childQuerySearch"
                    popper-class="my-autocomplete"
                    placeholder="输入儿童名称"
                    @select="childHandleSelect"
                >
                    <template #suffix>
                        <el-icon class="el-input__icon" @click="handleIconClick">
                            <edit />
                        </el-icon>
                    </template>
                    <template #default="{ item }">
                        <div class="value">{{ item.name }}</div>
                    </template>
                </el-autocomplete>
                <el-button type="primary" @click="childArrAdd">增加</el-button>
                <el-button type="danger" @click="childArrDel">减少</el-button>
            </div>
        </div>
        <div class="flex1 gap-4 items-between top10">
            <div class="showBox">
                {{ coashArr[0].toString() }}
            </div>
            <div class="showBox">
               {{ childArr[0].toString() }}
            </div>
        </div>
        <!--弹窗提交按钮-->
        <template #footer>
            <div class="dialog-footer top10">
                <el-button v-if="add_upate" type="primary" @click="sumbitAdd()">添加课程表</el-button>
                <div v-else>
                    <el-button type="primary" @click="sumbitUpdate()">修改课程表</el-button>
                    <el-button type="danger" @click="sumbitDelete(CourseObject.id)">删除课程表</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
/* 全局样式 */
.flex {
    display: flex;
}
.flex1 {
    display: flex;
    justify-content: space-around;
}
.top10{
    margin-top: 10px;
}
.box {
    height: 59px;
}
.course {
    height: 960px;
    width: 1400px;
    background-color: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* 左侧时间轴 */
.left {
    width: 7%;
    height: 100%;
    border-right: 1px solid #e0e0e0;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.TimeToDay {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #333;
    border-bottom: 1px solid #e0e0e0;
}

/* 右侧课程表 */
.right {
    width: 93%;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.top {
    display: flex;
    border-bottom: 1px solid #e0e0e0;
    background-color: #ffffff;
}
.top .topBox {
    flex: 1;
    height: 100%;
    padding: 10px;
    text-align: center;
    font-size: 14px;
    color: #555;
    border-right: 1px solid #e0e0e0;
}

/* 主体课程表 */
.main {
    flex: 1;
    display: flex;
    overflow: hidden;
}
.column {
    flex: 1;
    position: relative;
    border-right: 1px solid #e0e0e0;
}
.CourseBos {
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    background-color: #4caf50;
    color: white;
    font-size: 14px;
    text-align: center;
    line-height: 24px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    animation: fadeIn 0.5s ease-in-out;
}

/* 加载动画 */
.loading-animation {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    animation: pulse 1s infinite ease-in-out;
}
@keyframes pulse {
    0% {
        opacity: 0.6;
    }
    50% {
        opacity: 1;
    }
    100% {
        opacity: 0.6;
    }
}
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
.showBox{
    width: 50%;
    height: 70px;
    border: 1px solid #e0e0e0;
}

.my-autocomplete li {
  line-height: normal;
  padding: 7px;
}
.my-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
}
.my-autocomplete li .addr {
  font-size: 12px;
  color: #b4b4b4;
}
.my-autocomplete li .highlighted .addr {
  color: #ddd;
}
</style>